import React, { useState, useEffect, useCallback } from 'react';
import styles from '../index.module.scss';
import type { MenuProps } from 'antd';
import { OpenedMenu, MenuItem } from '/@/types/menu';
import Icon from '/@/components/icon';
import { Dropdown } from 'antd';
import { useStateOpenedMenu, useStateCurrentPath, useDispatchMenu } from '/@/store/hooks/menu';
import { useNavigate } from 'react-router';
import { useStateThemeConfig } from '/@/store/hooks/theme';
import { t } from 'i18next';
const items: MenuProps['items'] = [
  {
    label: 'menu.tagsview.refresh',
    key: 'refresh',
    icon: <Icon icon='icon-shuaxin'></Icon>,
  },
  {
    label: 'menu.tagsview.close',
    key: 'close',
    icon: <Icon icon='icon-cuowuguanbiquxiao'></Icon>,
  },
  {
    label: 'menu.tagsview.closeother',
    key: 'closeother',
    icon: <Icon icon='icon-cuowuguanbiquxiao-xianxingyuankuang'></Icon>,
  },
  {
    label: 'menu.tagsview.closeall',
    key: 'closeall',
    icon: <Icon icon='icon-quanbuguanbi'></Icon>,
  },
  {
    label: 'menu.tagsview.currentpage',
    key: 'currentpage',
    icon: <Icon icon='ExpandOutlined'></Icon>,
  },
];
export default function TagsView() {
  const { IsTagsViewIcon } = useStateThemeConfig();
  const [data, setData] = useState<OpenedMenu[]>([]);
  const openedMenu = useStateOpenedMenu();
  const { stateFilterOpenMenuKey: filterOpenMenu, stateStateCurrFull } = useDispatchMenu();
  //当前路由路径
  const currentPath = useStateCurrentPath();
  //路由跳转
  const navigate = useNavigate();
  //过滤右键下拉菜单
  const menuItemlist = useCallback(
    (item: OpenedMenu) => {
      let FilterItems = items?.map((v: any) => {
        return {
          label: t(v.label),
          key: v.key,
          icon: v.icon,
        };
      });
      let findList = FilterItems && [...FilterItems];
      return item.isAffix === true ? (findList && delete findList[1] ? findList : []) : FilterItems;
    },
    [data, openedMenu]
  );
  // 根据 选中的菜单 往里添加
  useEffect(() => {
    if (data.length !== openedMenu.length) {
      let old = [...data];
      openedMenu.forEach((item: OpenedMenu) => {
        if (!data.find((i) => i.path === item.path)) {
          old.push(item);
        }
      });
      old = old.filter((i) => openedMenu.find((item: OpenedMenu) => item.path === i.path));
      setData(old);
    }
  }, [openedMenu, data]);
  // 关闭当前顶部菜单
  const closeCurrent = useCallback(
    (item: OpenedMenu) => {
      const newData = data.filter((i) => i.path !== item.path);
      const next = newData[newData.length - 1];
      if (next) {
        setData(newData);
      }
      filterOpenMenu(newData as any[]);
      const isCurrent = item.path === currentPath;
      if (next && isCurrent) {
        navigate(next.path, { replace: true });
      } else if (isCurrent && !next) {
        navigate('/', { replace: true });
      }
    },
    [data, currentPath, navigate]
  );
  //关闭其他
  const closeOtherTagsView = useCallback(
    (path: string) => {
      let res = data.filter((item: MenuItem) => item.isAffix === true);
      let arr = data.filter((item: MenuItem) => item.path === path);
      filterOpenMenu(Array.from(new Set([...res, ...arr])) as any);
      navigate(path, { replace: true });
    },
    [data, filterOpenMenu, navigate]
  );
  //关闭全部
  const closeAll = useCallback(() => {
    let res = data.filter((item: MenuItem) => item.isAffix === true);
    filterOpenMenu(res as any);
    navigate('/', { replace: true });
  }, [data, filterOpenMenu, navigate]);
  return (
    <div className={styles.tagsView}>
      <div className={styles.scrollbar}>
        <ul className={styles.layout_navbars_tagsview_ul}>
          {data.map((item) => {
            const iconClick: React.MouseEventHandler<HTMLSpanElement> = (e) => {
              e.preventDefault();
              e.stopPropagation();
              closeCurrent(item);
            };
            return (
              <Dropdown
                menu={{
                  items: menuItemlist(item),
                  onClick: ({ key }) => {
                    switch (key) {
                      case 'refresh':
                        //console.log('刷新');
                        break;
                      case 'close':
                        closeCurrent(item);
                        break;
                      case 'closeother':
                        closeOtherTagsView(item.path);
                        break;
                      case 'closeall':
                        closeAll();
                        break;
                      case 'currentpage':
                        stateStateCurrFull(true);
                        break;
                    }
                  },
                }}
                trigger={['contextMenu']}
                key={item.path}
              >
                <li
                  className={`${styles.layout_navbars_tagsview_ul_li} ${
                    item.path === currentPath ? styles['is-active'] : ''
                  }`}
                  onClick={() => {
                    navigate(item.path);
                  }}
                >
                  {item.path !== currentPath && item.icon && IsTagsViewIcon && (
                    <Icon icon={item.icon} style={{ fontSize: '12px', marginRight: '5px' }}></Icon>
                  )}
                  <label>{t(item.title)}</label>
                  {item.path === currentPath && (
                    <Icon icon='icon-shuaxin' style={{ marginLeft: '5px', fontSize: '14px' }}></Icon>
                  )}
                  {item.path === currentPath && !item.isAffix && (
                    <Icon
                      icon='icon-cuowuguanbiquxiao'
                      style={{ marginLeft: '5px', fontSize: '14px' }}
                      onClick={iconClick}
                    ></Icon>
                  )}
                </li>
              </Dropdown>
            );
          })}
        </ul>
      </div>
    </div>
  );
}
